<template>
  <el-dialog :title="dialogTitle" :close-on-click-modal="false" :visible.sync="messageShow" :before-close="canel" class="view">
    <el-form ref="dataForm" :model="form" :rules="dataRule" label-width="150px" style="width: 600px;">
      <el-form-item label="消息名称" prop="msgName">
        <el-input v-model="form.msgName"></el-input>
      </el-form-item>
      <el-form-item label="消息内容" prop='msgContext'>
        <el-input type="textarea" :autosize="{ minRows: 5}" v-model="form.msgContext"></el-input>
      </el-form-item>
      <el-form-item label="跳转链接" prop='jumpLink'>
        <el-input v-model="form.jumpLink"></el-input>
      </el-form-item>
      <el-form-item label="发送范围" prop='msgScope'>
        <el-select v-model="form.msgScope" placeholder="请选择通知操作">
          <el-option v-for="(item, index) in steward" :key="index" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发送时间" prop='immediatelyState'>
        <el-radio-group v-model="form.immediatelyState">
          <el-radio label="1" :disabled="form.id>0">立即推送</el-radio>
          <el-radio label="0" :disabled="form.id>0">定时发送</el-radio>
        </el-radio-group>
        <el-date-picker
          v-if="form.immediatelyState === '0'"
          v-model="form.pushTime"
          type="datetime"
          placeholder="选择推送时间"
          style="margin-left: 20px;"
          @change="changeTime"
          :disabled="form.id>0"
          value-format="yyyy-MM-dd HH:mm:ss">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="onSubmit">{{ messBtn }}</el-button>
      <el-button @click="canel">取消</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      const validatePushTimeType = (rule, value, callback) => {
        if (this.form.immediatelyState === '0' && !this.form.pushTime) {
          console.log('请选择推送时间')
          callback(new Error('请选择推送时间'))
        } else {
          callback()
        }
      };
      return {
        messBtn: '',
        dialogTitle: '',
        steward: [{label: '全部用户', value: 0},
          {label: '会员', value: 2},
          {label: '非会员', value: 1}],
        rember: '0',
        form: {},
        value1: '',
        options: [{
          value: '0',
          label: '本人'
        }, {
          value: '1',
          label: '上级'
        }, {
          value: '2',
          label: '上上级'
        }],
        resource: '',
        pushTime: '',
        messageShow: false,
        dataRule: {
          msgName: [
            { required: true, message: "消息名称不能为空", trigger: "blur" }
          ],
          msgContext: [
            { required: true, message: "消息内容不能为空", trigger: "blur" }
          ],
          jumpLink: [
            // { required: true, message: "跳转链接不能为空", trigger: "blur" },
            {pattern:/(http|https|yiban):\/\/([\w.]+\/?)\S*/,message: '只能输入以http、https、yiban开头的网址', trigger: 'blur'}
          ],
          msgScope: [
            { required: true, message: "发送范围不能为空", trigger: "change" }
          ],
          immediatelyState: [
            { required: true, message: "发送时间不能为空", trigger: "change" }
          ]
        },
      }
    },
    methods: {
      initData (id) {
        this.form.id = id || 0;
        this.messageShow = true
        if (id) {
          this.dialogTitle = '修改'
          this.messBtn = '确认修改'
          const that = this
          this.$http({
            url: this.$http.adornUrl(`/user/msgtemplate/info/${id}`),
            method: "get",
          }).then(({ data }) => {
            data.msgTemplate.immediatelyState = data.msgTemplate.immediatelyState.toString()
            if (data.msgTemplate.immediatelyState === '0') {
              that.pushTime = data.msgTemplate.pushTime
            }
            that.form = data.msgTemplate
          })
        } else {
          this.dialogTitle = '新增'
          this.messBtn = '立即创建'
        }
      },
      changeTime () {
        if (new Date(this.form.pushTime).getTime() < new Date().getTime()) {
          this.form.pushTime = ''
          this.$message.error('所选时间要大于当前时间')
        }
      },
      setButler () {
        // const data = {
        //   userId: this.id,
        //   superiorUid: this.steward[this.rember].userId
        // }
        // this.$http({
        //   url: this.$http.adornUrl(`/sale/saleRelation/update`),
        //   method: "post",
        //   data
        // }).then(({ data }) => {
        //   console.log(data)
        // })
      },
      canel() {
        this.messageShow = false
        this.$refs["dataForm"].resetFields()
        this.form.pushTime = ''
      },
      onSubmit () {
        this.form.msgType = 1
        if (this.form.immediatelyState === '1') {
          this.form.pushTime = this.formate()
        }
        this.form.pushRate = '0'
        this.$refs["dataForm"].validate(valid => {
          if (valid) {
            if (this.dialogTitle === '修改') {
              this.$http({
                url: this.$http.adornUrl("/user/msgtemplate/update"),
                method: "post",
                data: this.$http.adornData(this.form)
              }).then(({data}) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.messageShow = false
                    this.$emit('updatTable')
                    this.$refs["dataForm"].resetFields()
                    this.form.pushTime = ''
                  }
                });
              })
            } else {
              this.$http({
                url: this.$http.adornUrl("/user/msgtemplate/save"),
                method: "post",
                data: this.$http.adornData(this.form)
              }).then(({data}) => {
                this.$message({
                  message: "添加成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.messageShow = false
                    this.$emit('updatTable')
                    this.$refs["dataForm"].resetFields()
                    this.form.pushTime = ''
                  }
                });
              })
            }
          }
        })
      },
      goBack () {
        this.$emit('goBack')
      },
      formate() {
        var date = new Date();
        var y = date.getFullYear();
        var m = date.getMonth() + 1;
        m = m < 10 ? ('0' + m) : m;
        var d = date.getDate();
        d = d < 10 ? ('0' + d) : d;
        var h = date.getHours();
        h = h < 10 ? ('0' + h) : h;
        var minute = date.getMinutes();
        var second = date.getSeconds();
        minute = minute < 10 ? ('0' + minute) : minute;
        second = second < 10 ? ('0' + second) : second;
        return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second
      }
    }
  };
</script>
<style>
  .otherContent{
    padding: 40px 60px;
  }
  .el-row{
    display: flex;
    align-items: center;
    height: 45px;
    font-size: 16px;
  }
</style>
